package com.winner;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AQSDemo {

    // 共享的数据
    private static Integer count = 0;

    private static Lock lock = new ReentrantLock(); // 重入锁 独占锁  排他锁 都是  写到这里的原因是 多个线程都用的这一把锁
    // 看其构造, 默认是 new NonfairSync(); 非公平锁

    //定义操作的方法
    private static void incr() {
        try {
            Thread.sleep(10);
            lock.lock(); // 加锁操作  lock unlock  将原来并行的操作 抓换为 串行的操作了  效率低了
            count++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock(); // 释放锁
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        for (int i = 0; i < 1000; i++) {
            new Thread(()-> {
                incr();
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        // 等待1000 个子线程走完后获取最终的结果
        System.out.println(count);
    }

}
